import Vue from 'vue';
import _ from 'lodash';

let resizeKey = 0;
const resizeEvent = {};
Vue.directive('resize', {
  // 当被绑定的元素插入到 DOM 中时……
  inserted: function(el, binding) {
    resizeKey++;
    el.setAttribute('resizeKey', resizeKey);
    if (typeof binding.value === 'function') {
      resizeEvent[resizeKey] = binding.value;
    }
  },
  unbind: function(el) {
    //组件销毁时移除事件
    var key = el.getAttribute('resizeKey');
    delete resizeEvent[key];
  },
});

window.addEventListener(
  'resize',
  _.debounce(function() {
    Object.keys(resizeEvent).forEach(key => {
      const event = resizeEvent[key];
      if (typeof event === 'function') {
        event();
      }
    });
  }, 100)
);
